#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|= Message Customizer
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Customize certain messages the bot displays.
|===== Additional Comments: =================================
|= To get a message format use: 
|= "formatmessage(<jid>, <message>, <default> [, keyword values])"
|= JID : The user you're getting the format from.
|= Message : The name of the message. (eg. Main or Names)
|= Default : The default message format used if the user hasn't set one.
|= Keyword Values: Pass the values in keyword format, doing this will
|=	return an interpolated string.
|= For more examples check out "cmd_names" in the info plugin
|=	and "sendtoall" in cbot2.
|============================================================"""

import traceback

from ini import userlist
from utils import *


if not os.path.isdir("errors"):
	os.mkdir("errors")
	print "ALERT: Log directory doesn't exist, making folder \errors\\"
global customlog
customlog = file(os.path.join("errors","CustomError.log"), "a+")

def init(bot):
	bot.addCommand("custom", cmd_custom)
	
	global presets
	presets = {
		"main": {
			"msn":"*%(name)s* says:\n %(msg)s"
		},
		"names": {
			"online":"Users Available: (%(d_on)d)\n%(on)s",
			"all-online":"Users:\nIdle: (%(d_idle)d)\n%(idle)s\n\nAway: (%(d_away)d)\n%(away)s\n\nBusy: (%(d_busy)d)\n%(busy)s\n\nAvailable: (%(d_on)d)\n%(on)s",
			"offline":"Users Offline: (%(d_off)s)\n%(off)s"
		}
	}
	
def unload(bot):
	bot.removeCommand('custom')

def cmd_custom(bot, user, args):
	"""Customize message formating.
	Usage: /custom <command> <message> [<string>]
	
	Commands:
	* Help - What you need to know for each message.
	* List - List the currently overwriten messages.
	* Set - Overwrite a message's formating.
	* Del - Revert a message to it's original format.
	 
	Messages:
	* main - The messages that you get when people talk.
	* names - The )names message.
	
	Note: To use presets put the name in place of a normal string."""
	
	user = getjid(user)
	
	try:
		cmd, msg = args.split(' ',1)
	except:
		if cmd == "list":
			sub_list(bot, user)
		else:
			bot.error(user, "There was an error with your message, please check it and try again.")
			return
	
	cmd = cmd.lower()
	cmd = cmd.replace("add", "set", 1)
		
	if cmd == "help":
		sub_help(bot, user, msg)
		
	elif ' ' in msg or cmd == "del":
		if cmd != "del":
			msg, format = msg.split(' ',1)
			msg = msg.lower()
			format = '\n'.join(format.split('\\n'))
		else:
			util_del(bot, user, msg)
			return
			
		try:
			eval("sub_%s" % msg)(bot, user, msg, cmd, format)
		except ValueError:
			bot.error(user, "It seems you've made a typo in your string, probably in one of the variables.")
		except KeyError:
			traceback.print_exc()
			bot.error(user, "You used an invalid variable, please check the available variables by typing )custom help <message>.")
		except NameError:
			bot.error(user, "The message(%s) you're trying to change doesn't exist. Try again!" % msg)
		except:
			util_error(bot, user)
	else:
		bot.error(user, "Please add a format you want to use.")
		
def sub_help(bot, user, msg):
	"""Read the doc string for each message."""
	#sub = util_getmsg(msg)
	try:
		bot.msg(user, eval("sub_%s" % msg).__doc__)
	except NameError:
		bot.msg(user, "That message doesn't exist, please check it and try again.")
	except:
		util_error(bot)
		
def sub_list(bot, user):
	"""List all the customized messages."""
	user = getjid(user)
	list = []
	for i in userlist[user]:
		if i.endswith("_format"):
			list.append([i,userlist[user].get(i)])
			lost.sort()
	for [i,j] in list:
		msg += i +" | "+ j +"\n"
	bot.msg(user, msg)

def sub_main(bot, user, msg, cmd, format):
	"""This is the output format for normal chatting.
	
	Variables:
	* name - The name of the user sending the message.
	* msg - The actual message being sent.
	 
	Examples:
	* <%(name)s> %(msg)s
	* %(names)s says:\\n %(msg)s
	
	Presets:
	* MSN - Displays messages in an MSN-esque style."""
		
	if cmd == "set":
		format = util_getPreset(msg, format)
		
		str(format % {"time":time.strftime('%I:%M %p'), "name":"Hawk", "msg":"Hey dude! What's up?"})
		set_userflag(user, msg + "_format", format)
		bot.msg(user, "Your custom message has been set and will look like this:\n" + format % {"time":time.strftime('%I:%M %p'),"name":"Hawk", "msg":"Hey dude! What's up?"})
	
	
def sub_names(bot, user, msg, cmd, format):
	"""This is the output format for )names.
		
	Variables:
	 Note: For the number of users in a group prefix the variable with 'd_'
	* off - List of offline users.
	* on - List of available users.
	* idle - All idle users.
	* away - All away users.
	* busy - All busy users.
	* total - All users in order of Online, Busy, Idle, Offline.
	
	Examples:
	* Users:\\nOffline: (%(d_off)d)\\n%(off)s\\n\\nAway: (%(d_idle)d)\\n%(idle)s\\n\\nBusy: (%(d_busy)d)\\n%(busy)s\\n\\nAvailable: (%(d_on)d)\\n%(on)s\\n\\nTotal: (%(d_total)d)
	* Users Available:\\n%(on)s
	 
	Presets:
	* Online - Shows only available users.
	* All-Online - Shows everyone but offline users.
	* Offline - Shows only offline users."""
	
	if cmd == "set":
		online = offline = away = idle = busy = ['this', 'is', 'a', 'test']
		format = util_getPreset(msg, format)
		
		str(format % {
			"d_off":len(offline), 
			"off":" ".join(offline), 
			"d_idle":len(idle), 
			"idle":" ".join(idle),
			"d_away":len(away),  
			"away":" ".join(away), 
			"d_busy":len(busy), 
			"on":" ".join(online), 
			"busy":" ".join(busy), 
			"d_on":len(online), 
			"d_total":len(online + offline + away + busy), 
			"total":(online + busy + away + offline)
		})
		set_userflag(user, msg + "_format", format)
		bot.msg(user, "Your custom message has been set. Type )names to test it out!")
			
def util_del(bot, user, key):
	key = key + "_format"
	if userlist[user][key]:
		del userlist[user][key]
		bot.msg(user, "Bai Bai, custom message! T.T")
	else:
		bot.error(user, "You haven't customized this message yet.")
			
def util_getPreset(msg, format):
	"""Return a format if 'format' is the name of a preset."""
	if presets[msg].has_key(format.lower()):
		return presets[msg][format.lower()]
	return format
			
def util_error(bot, user):
	traceback.print_exc()
	print >>customlog, "\n"
	traceback.print_exc(None, customlog)
	customlog.close()
	bot.error(user, "Uh-oh, something bad and/or unknown happened! Error reported.")
	
def util_getmsg(msg):
	"""Get the command for each message."""
	if msg == "main":
		return sub_main()
		
	if msg == "names":
		return sub_names()
		
	return False
